{% extends 'base.html' %}
{% load static %}

{% block content %}
<!-- 搜索栏和位置 -->
<section class="bg-primary text-white py-5">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 mx-auto text-center">
                <h1 class="display-4 mb-4">发现身边的精彩活动</h1>
                <div class="row g-3">
                    <div class="col-md-8">
                        <div class="input-group">
                            <input type="text" id="searchInput" class="form-control form-control-lg" placeholder="搜索活动、地点或兴趣...">
                            <button class="btn btn-light" type="button" onclick="searchActivities()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <button class="btn btn-outline-light btn-lg w-100" onclick="getLocationAndUpdateMap()">
                            <i class="fas fa-location-arrow"></i> 定位到我
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- 热门活动推荐 -->
<section class="py-5 bg-light">
    <div class="container">
        <div class="row mb-4">
            <div class="col">
                <h2 class="h4">🔥 热门活动推荐</h2>
                <p class="text-muted">浏览数最高的活动</p>
            </div>
            <div class="col-auto">
                <a href="{% url 'location:activity_list' %}" class="btn btn-outline-primary">查看全部</a>
            </div>
        </div>

       <div class="row g-4" id="activitiesContainer">
            {% for event in popular_events %}
            <div class="col-md-3">
                <div class="card activity-card h-100" onclick="viewActivityDetail({{ event.id }})">
                    <!-- 修改图片显示部分 -->
                    <div style="height: 200px; overflow: hidden; position: relative;">
    {% if event.image_url %}
        <img src="{{ event.image_url }}"
             class="card-img-top"
             alt="{{ event.title }}"
             style="width: 100%; height: 100%; object-fit: cover;"
             onerror="handleEventImageError(this, {{ event.id }})">
    {% else %}
        <div class="image-placeholder" style="display: flex; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(135deg, #f8f9fa, #e9ecef); align-items: center; justify-content: center;">
            <i class="fas fa-calendar-alt fa-2x text-muted"></i>
        </div>
    {% endif %}
</div>
                    <div class="card-body">
                        <h5 class="card-title">{{ event.title|truncatechars:20 }}</h5>
                        <div class="d-flex justify-content-between text-muted small mb-2">
                            <span><i class="fas fa-map-marker-alt"></i> {{ event.location|truncatechars:10 }}</span>
                            <span><i class="fas fa-clock"></i> {{ event.start_time|date:"m月d日 H:i" }}</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="rating-stars">
                                {% for i in "12345"|make_list %}
                                    {% if forloop.counter <= event.avg_rating %}
                                        <i class="fas fa-star"></i>
                                    {% else %}
                                        <i class="far fa-star"></i>
                                    {% endif %}
                                {% endfor %}
                                <small class="text-muted">{{ event.avg_rating|default:"0.0" }}</small>
                            </div>
                            <span class="badge {% if event.is_free %}bg-success{% else %}bg-warning{% endif %}">
                                {% if event.is_free %}免费{% else %}¥{{ event.fee }}{% endif %}
                            </span>
                        </div>
                        <div class="mt-2">
                            <span class="badge bg-primary">{{ event.current_participants }}/{{ event.max_participants }}人</span>
                            <small class="text-muted float-end"><i class="fas fa-eye"></i> {{ event.views_count }}</small>
                        </div>
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="col-12 text-center py-5">
                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                <h5>暂无热门活动</h5>
                <p class="text-muted">当前没有热门活动，去看看其他活动吧</p>
                <a href="{% url 'location:activity_create' %}" class="btn btn-primary mt-3">
                    <i class="fas fa-plus"></i> 创建第一个活动
                </a>
            </div>
            {% endfor %}
        </div>
    </div>
</section>

<!-- 附近活动地图和搜索 -->
<section class="py-5">
    <div class="container">
        <div class="row mb-4">
            <div class="col">
                <h2 class="h4">🗺️ 附近活动地图</h2>
                <p class="text-muted">在地图上查看周边的活动位置</p>
            </div>
            <div class="col-auto">
                <button class="btn btn-outline-primary btn-sm" onclick="refreshMap()">
                    <i class="fas fa-sync-alt"></i> 刷新地图
                </button>
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row g-3 align-items-center">
                            <div class="col-md-3">
                                <label class="form-label"><strong>搜索活动或位置</strong></label>
                                <div class="input-group">
                                    <input type="text" id="mapSearchInput" class="form-control" placeholder="输入活动名称、地点或关键词...">
                                    <button class="btn btn-primary" type="button" onclick="searchMapActivities()">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label"><strong>活动分类</strong></label>
                                <select id="categoryFilter" class="form-select" onchange="filterMapActivities()">
                                    <option value="">全部分类</option>
                                    <!-- 将通过JavaScript动态加载 -->
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label"><strong>费用类型</strong></label>
                                <select id="feeFilter" class="form-select" onchange="filterMapActivities()">
                                    <option value="">全部</option>
                                    <option value="free">免费</option>
                                    <option value="paid">付费</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label"><strong>时间范围</strong></label>
                                <select id="timeFilter" class="form-select" onchange="filterMapActivities()">
                                    <option value="future">未来活动</option>
                                    <option value="recent">最近7天</option>
                                    <option value="past">过去活动</option>
                                    <option value="all">所有活动</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label"><strong>&nbsp;</strong></label>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-outline-secondary" onclick="clearMapFilters()">
                                        <i class="fas fa-times"></i> 清除筛选
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 活动列表区域 -->
            <div class="col-lg-6 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list me-2"></i>活动列表
                            <span class="badge bg-primary ms-2" id="activitiesCount">0</span>
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <div id="activitiesList" class="activities-list" style="max-height: 400px; overflow-y: auto;">
                            <div class="text-center py-5">
                                <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
                                <p>加载活动中...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 地图区域 -->
            <div class="col-lg-6 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-map me-2"></i>活动地图
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <div id="home-map-container" class="home-map-container" style="height: 400px;">
                            <div class="d-flex justify-content-center align-items-center h-100">
                                <div class="text-center">
                                    <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
                                    <p>地图加载中...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12 text-center">
                <a href="/location/activities/map/" class="btn btn-primary">
                    <i class="fas fa-map"></i> 查看完整地图
                </a>
            </div>
        </div>
    </div>
</section>

<!-- 定位状态提示 -->
<div id="locationStatus" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1050;">
    <div id="locationToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="fas fa-map-marker-alt text-primary me-2"></i>
            <strong class="me-auto">位置服务</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        <div class="toast-body" id="toastMessage">
            正在获取您的位置...
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
    .home-map-container {
        border: 1px solid #dee2e6;
        border-radius: 0 0 8px 8px;
        background: #f8f9fa;
    }

    .activity-card {
        transition: transform 0.2s, box-shadow 0.2s;
        cursor: pointer;
        border: none;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .activity-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }

    .rating-stars {
        color: #ffc107;
    }

    .map-marker-popup {
        max-width: 200px;
        padding: 8px;
    }

    .map-marker-popup img {
        width: 100%;
        height: 120px;
        object-fit: cover;
        border-radius: 4px;
        margin-bottom: 8px;
    }

    .activities-list {
        border-radius: 0 0 8px 8px;
    }

    .activity-list-item {
        padding: 12px 16px;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .activity-list-item:hover {
        background-color: #f8f9fa;
    }

    .activity-list-item:last-child {
        border-bottom: none;
    }

    .activity-list-item.active {
        background-color: #e7f1ff;
        border-left: 3px solid #0d6efd;
    }

    .activity-meta {
        font-size: 0.875rem;
        color: #6c757d;
    }

    .activity-badge {
        font-size: 0.75rem;
    }

    .image-placeholder {
    background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    border-radius: 8px 8px 0 0;
}

.activity-card {
    transition: transform 0.2s, box-shadow 0.2s;
    cursor: pointer;
    border: none;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.activity-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}
</style>
{% endblock %}

{% block scripts %}
<!-- 引入百度地图API -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=rUiyl00fneDC8rieZJagiXxwyDl7ZYje"></script>

<script>
// 全局变量
let homeMap = null;
let currentLocation = null;
let allActivities = [];
let filteredActivities = [];
let currentMarkers = [];

// 初始化首页地图
function initHomeMap() {
    try {
        console.log('🗺️ 开始初始化地图...');
        // 创建地图实例，默认显示北京
        homeMap = new BMap.Map("home-map-container");
        const point = new BMap.Point(116.404, 39.915);
        homeMap.centerAndZoom(point, 13);
        homeMap.enableScrollWheelZoom(true);

        // 添加基本控件
        homeMap.addControl(new BMap.NavigationControl());
        homeMap.addControl(new BMap.ScaleControl());

        // 从服务器获取活动数据并添加标记
        loadActivitiesAndUpdateDisplay();

        console.log('✅ 首页地图初始化成功');
    } catch (error) {
        console.error('❌ 地图初始化失败:', error);
        showToast('地图初始化失败，请刷新页面重试', 'error');
    }
}

// 从服务器加载活动数据
function loadActivitiesAndUpdateDisplay() {

    // 获取筛选参数
    const searchTerm = document.getElementById('mapSearchInput').value.trim();
    const categoryFilter = document.getElementById('categoryFilter').value;
    const feeFilter = document.getElementById('feeFilter').value;
    const timeFilter = document.getElementById('timeFilter').value;

    // 构建查询参数
    const params = new URLSearchParams();
    if (searchTerm) {
        params.append('search', searchTerm);
    }
    if (categoryFilter) params.append('category', categoryFilter);
    if (feeFilter) params.append('fee', feeFilter);
    if (timeFilter) params.append('time', timeFilter);

    const apiUrl = `/location/api/nearby-activities/?${params}`;

    // 显示加载状态
    const activitiesList = document.getElementById('activitiesList');
    activitiesList.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-spinner fa-spin fa-2x text-primary mb-2"></i>
            <p>加载活动中...</p>
        </div>
    `;

    // 使用正确的API路径
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                allActivities = data.activities;
                filteredActivities = [...allActivities];
                updateActivitiesList();
                updateActivitiesCount();
                addActivityMarkers(filteredActivities);

                // 显示搜索结果提示
                const timeFilterText = getTimeFilterText(timeFilter);
                if (searchTerm) {
                    if (filteredActivities.length > 0) {
                        showToast(`在${timeFilterText}中找到 ${filteredActivities.length} 个相关活动`, 'success');
                    } else {
                        showToast(`在${timeFilterText}中没有找到包含"${searchTerm}"的活动`, 'warning');
                    }
                } else {
                    showToast(`找到 ${filteredActivities.length} 个${timeFilterText}`, 'info');
                }
            } else {
                console.error('❌ 加载活动数据失败:', data.message);
                showToast('加载活动数据失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('❌ 加载活动数据失败:', error);
            showToast('加载活动数据失败，请检查网络连接', 'error');
        });
}

// 搜索地图活动
function searchMapActivities() {
    const searchTerm = document.getElementById('mapSearchInput').value.trim();

    if (searchTerm) {
        showToast(`正在搜索: ${searchTerm}`, 'info');
        loadActivitiesAndUpdateDisplay();
    } else {
        showToast('请输入搜索关键词', 'warning');
        // 如果没有搜索词，也重新加载数据
        loadActivitiesAndUpdateDisplay();
    }
}

// 筛选地图活动
function filterMapActivities() {
    loadActivitiesAndUpdateDisplay();
}

// 清除地图筛选条件
function clearMapFilters() {
    document.getElementById('mapSearchInput').value = '';
    document.getElementById('categoryFilter').value = '';
    document.getElementById('feeFilter').value = '';
    document.getElementById('timeFilter').value = 'future';

    loadActivitiesAndUpdateDisplay();
    showToast('已清除所有筛选条件', 'info');
}

// 获取时间筛选的显示文本
function getTimeFilterText(timeFilter) {
    const timeMap = {
        'future': '未来活动',
        'recent': '最近7天活动',
        'past': '过去活动',
        'all': '所有活动'
    };
    return timeMap[timeFilter] || '活动';
}

// 更新活动列表显示
function updateActivitiesList() {
    const activitiesList = document.getElementById('activitiesList');

    if (!filteredActivities || filteredActivities.length === 0) {
        activitiesList.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-search fa-2x text-muted mb-2"></i>
                <p class="text-muted">没有找到匹配的活动</p>
                <button class="btn btn-sm btn-outline-primary" onclick="clearMapFilters()">清除筛选条件</button>
            </div>
        `;
        return;
    }

    let html = '';
    filteredActivities.forEach((activity, index) => {
        // 根据状态添加不同的样式
        let statusBadge = '';
        if (activity.status === 'past') {
            statusBadge = '<span class="badge bg-secondary ms-1">已结束</span>';
        } else if (activity.status === 'soon') {
            statusBadge = '<span class="badge bg-warning ms-1">即将开始</span>';
        }

        html += `
            <div class="activity-list-item" onclick="focusOnActivity(${index})">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <h6 class="mb-0 flex-grow-1">
                        ${activity.title || '未命名活动'}
                        ${statusBadge}
                    </h6>
                    <span class="badge ${activity.is_free ? 'bg-success' : 'bg-warning'} activity-badge">
                        ${activity.is_free ? '免费' : '¥' + (activity.fee || 0)}
                    </span>
                </div>
                <div class="activity-meta">
                    <div class="mb-1">
                        <i class="fas fa-map-marker-alt me-1"></i>
                        ${activity.address || activity.location || '地址未提供'}
                    </div>
                    <div class="mb-1">
                        <i class="fas fa-clock me-1"></i>
                        ${activity.time || '时间未设置'}
                    </div>
                    <div class="d-flex justify-content-between">
                        <span><i class="fas fa-tag me-1"></i>${activity.category || '未分类'}</span>
                        <span class="badge bg-primary activity-badge">
                            ${activity.current_participants || 0}/${activity.max_participants || 0}人
                        </span>
                    </div>
                </div>
            </div>
        `;
    });

    activitiesList.innerHTML = html;
}

// 更新活动数量显示
function updateActivitiesCount() {
    const countElement = document.getElementById('activitiesCount');
    if (countElement) {
        countElement.textContent = filteredActivities.length;
    }
}

// 添加活动标记到地图
function addActivityMarkers(activities) {
    if (!homeMap) {
        console.log('❌ 地图未初始化，无法添加标记');
        return;
    }

    // 清除现有标记
    clearAllMarkers();

    if (!activities || activities.length === 0) {
        console.log('ℹ️ 没有找到活动数据');
        return;
    }

    console.log(`🗺️ 添加 ${activities.length} 个活动标记到地图`);

    // 为每个活动添加标记
    activities.forEach((activity, index) => {
        if (!activity.location || !activity.location.lat || !activity.location.lng) {
            console.warn('⚠️ 活动缺少位置信息:', activity.title);
            return;
        }

        const point = new BMap.Point(activity.location.lng, activity.location.lat);
        const marker = new BMap.Marker(point);

        // 创建信息窗口内容
        const content = `
            <div class="map-marker-popup">
                <img src="${activity.image || 'https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60'}"
                     alt="${activity.title}"
                     onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60'">
                <h6 style="margin: 8px 0; font-size: 14px;">${activity.title || '未命名活动'}</h6>
                <p class="mb-1"><small><i class="fas fa-map-marker-alt"></i> ${activity.address || '地址未提供'}</small></p>
                <p class="mb-1"><small><i class="fas fa-clock"></i> ${activity.time || '时间未设置'}</small></p>
                <p class="mb-1"><small><i class="fas fa-tag"></i> ${activity.category || '未分类'}</small></p>
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <div class="rating-stars">
                        ${generateStarRating(activity.rating || 0)}
                        <small class="text-muted">${activity.rating || 0}</small>
                    </div>
                    <span class="badge ${activity.is_free ? 'bg-success' : 'bg-warning'}">
                        ${activity.is_free ? '免费' : '¥' + (activity.fee || 0)}
                    </span>
                </div>
                <button class="btn btn-sm btn-primary w-100 mt-2" onclick="viewActivityDetailFromMap(${activity.id})">
                    <i class="fas fa-info-circle"></i> 查看详情
                </button>
            </div>
        `;

        const infoWindow = new BMap.InfoWindow(content, {
            width: 240,
            height: 320
        });

        marker.addEventListener("click", function() {
            this.openInfoWindow(infoWindow);
            highlightListItem(index);
        });

        homeMap.addOverlay(marker);
        currentMarkers.push(marker);
    });

    // 如果用户位置已知，添加用户位置标记
    if (currentLocation) {
        addUserLocationMarker();
    }
}

// 从地图查看活动详情
function viewActivityDetailFromMap(activityId) {
    if (activityId) {
        window.location.href = `/location/activity_detail/${activityId}/`;
    } else {
        showToast('活动ID无效', 'error');
    }
}

// 清除所有地图标记
function clearAllMarkers() {
    currentMarkers.forEach(marker => {
        homeMap.removeOverlay(marker);
    });
    currentMarkers = [];
}

// 高亮列表项
function highlightListItem(index) {
    const items = document.querySelectorAll('.activity-list-item');
    items.forEach((item, i) => {
        if (i === index) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
}

// 聚焦到特定活动
function focusOnActivity(index) {
    const activity = filteredActivities[index];
    if (!activity || !activity.location) return;

    highlightListItem(index);

    const point = new BMap.Point(activity.location.lng, activity.location.lat);
    homeMap.panTo(point);
    homeMap.setZoom(15);

    if (currentMarkers[index]) {
        const marker = currentMarkers[index];
        const content = `
            <div class="map-marker-popup">
                <img src="${activity.image || 'https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60'}"
                     alt="${activity.title}"
                     onerror="this.onerror=null; this.src='https://images.unsplash.com/photo-1546519638-68e109498ffc?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60'">
                <h6 style="margin: 8px 0; font-size: 14px;">${activity.title || '未命名活动'}</h6>
                <p class="mb-1"><small><i class="fas fa-map-marker-alt"></i> ${activity.address || '地址未提供'}</small></p>
                <p class="mb-1"><small><i class="fas fa-clock"></i> ${activity.time || '时间未设置'}</small></p>
                <p class="mb-1"><small><i class="fas fa-tag"></i> ${activity.category || '未分类'}</small></p>
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <div class="rating-stars">
                        ${generateStarRating(activity.rating || 0)}
                        <small class="text-muted">${activity.rating || 0}</small>
                    </div>
                    <span class="badge ${activity.is_free ? 'bg-success' : 'bg-warning'}">
                        ${activity.is_free ? '免费' : '¥' + (activity.fee || 0)}
                    </span>
                </div>
                <button class="btn btn-sm btn-primary w-100 mt-2" onclick="viewActivityDetailFromMap(${activity.id})">
                    <i class="fas fa-info-circle"></i> 查看详情
                </button>
            </div>
        `;

        const infoWindow = new BMap.InfoWindow(content, {
            width: 240,
            height: 320
        });
        marker.openInfoWindow(infoWindow);
    }
}

// 生成星级评分HTML
function generateStarRating(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    let stars = '';

    for (let i = 0; i < fullStars; i++) {
        stars += '<i class="fas fa-star"></i>';
    }
    if (hasHalfStar) {
        stars += '<i class="fas fa-star-half-alt"></i>';
    }
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
    for (let i = 0; i < emptyStars; i++) {
        stars += '<i class="far fa-star"></i>';
    }
    return stars;
}

// 获取位置并更新地图
function getLocationAndUpdateMap() {
    showToast('正在获取您的位置...', 'info');

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                currentLocation = { lat, lng };

                const point = new BMap.Point(lng, lat);
                homeMap.centerAndZoom(point, 15);

                addUserLocationMarker();
                loadActivitiesAndUpdateDisplay();

                showToast('位置获取成功！', 'success');
                sendUserLocationToServer(lat, lng);
            },
            function(error) {
                console.error('获取位置失败:', error);
                let message = '获取位置失败';
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        message = '位置访问被拒绝，请在浏览器设置中允许位置访问';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        message = '位置信息不可用';
                        break;
                    case error.TIMEOUT:
                        message = '位置请求超时';
                        break;
                }
                showToast(message, 'error');
            },
            {
                enableHighAccuracy: true,
                timeout: 15000,
                maximumAge: 60000
            }
        );
    } else {
        showToast('浏览器不支持地理位置服务', 'error');
    }
}

// 发送用户位置到服务器
function sendUserLocationToServer(lat, lng) {
    fetch('/api/user-location/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            lat: lat,
            lng: lng
        })
    }).catch(error => {
        console.error('发送位置到服务器失败:', error);
    });
}

// 获取CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 添加用户位置标记
function addUserLocationMarker() {
    if (!currentLocation || !homeMap) return;

    const point = new BMap.Point(currentLocation.lng, currentLocation.lat);
    const marker = new BMap.Marker(point);

    homeMap.addOverlay(marker);
}

// 显示提示信息
function showToast(message, type = 'info') {
    const toastElement = document.getElementById('locationToast');
    if (!toastElement) return;

    const toastMessage = document.getElementById('toastMessage');
    const toastHeader = toastElement.querySelector('.toast-header i');

    toastMessage.textContent = message;

    const icons = {
        'info': 'fa-info-circle text-primary',
        'success': 'fa-check-circle text-success',
        'error': 'fa-exclamation-circle text-danger',
        'warning': 'fa-exclamation-triangle text-warning'
    };

    toastHeader.className = `fas ${icons[type] || 'fa-info-circle text-primary'} me-2`;

    const toast = new bootstrap.Toast(toastElement);
    toast.show();
}

// 刷新地图
function refreshMap() {
    showToast('刷新地图数据...', 'info');
    loadActivitiesAndUpdateDisplay();
}

// 搜索活动（顶部搜索栏）
function searchActivities() {
    const query = document.getElementById('searchInput').value.trim();
    if (query) {
        window.location.href = `/location/activities/?q=${encodeURIComponent(query)}`;
    } else {
        showToast('请输入搜索关键词', 'warning');
    }
}

// 查看活动详情
function viewActivityDetail(activityId) {
    if (activityId) {
        window.location.href = `/location/activity_detail/${activityId}/`;
    } else {
        showToast('活动ID无效', 'error');
    }
}

// 页面加载时获取分类数据
function loadCategories() {
    fetch('/location/api/categories/')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                populateCategoryFilter(data.categories);
            } else {
                console.error('获取分类数据失败:', data.message);
            }
        })
        .catch(error => {
            console.error('获取分类数据失败:', error);
            // 使用默认分类作为备选
            const defaultCategories = [
                {name: '户外运动'},
                {name: '文化艺术'},
                {name: '社交聚会'},
                {name: '学习分享'},
                {name: '其他'}
            ];
            populateCategoryFilter(defaultCategories);
        });
}

// 填充分类筛选下拉菜单
function populateCategoryFilter(categories) {
    const categoryFilter = document.getElementById('categoryFilter');
    if (!categoryFilter) return;

    while (categoryFilter.children.length > 1) {
        categoryFilter.removeChild(categoryFilter.lastChild);
    }

    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.name;
        option.textContent = category.name;
        categoryFilter.appendChild(option);
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 首页初始化开始...');

    // 先加载分类数据
    loadCategories();

    // 设置搜索框事件监听
    const mapSearchInput = document.getElementById('mapSearchInput');
    if (mapSearchInput) {
        mapSearchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                console.log('🔍 回车键触发搜索');
                searchMapActivities();
            }
        });

        // 添加输入监听，实时显示搜索状态
        mapSearchInput.addEventListener('input', function(e) {
            const searchTerm = e.target.value.trim();
            if (searchTerm.length > 0) {
                console.log('🔍 输入内容:', searchTerm);
            }
        });
    }

    // 延迟初始化地图，确保DOM完全加载
    setTimeout(() => {
        try {
            initHomeMap();
            console.log('✅ 首页初始化完成');
        } catch (error) {
            console.error('❌ 首页初始化失败:', error);
        }
    }, 1000);
});

// 处理活动图片加载错误
function handleEventImageError(imgElement, eventId) {
    console.log('活动图片加载失败，事件ID:', eventId);

    // 显示占位符
    const placeholder = imgElement.nextElementSibling;
    if (placeholder && placeholder.classList.contains('image-placeholder')) {
        placeholder.style.display = 'flex';
    }
    imgElement.style.display = 'none';

    // 尝试从服务器获取图片URL
    fetchEventImage(eventId, imgElement);
}

// 从服务器获取活动图片URL
function fetchEventImage(eventId, imgElement) {
    fetch(`/location/api/event-image/${eventId}/`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取图片失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.image_url) {
                // 重新设置图片源
                imgElement.src = data.image_url;
                imgElement.style.display = 'block';

                const placeholder = imgElement.nextElementSibling;
                if (placeholder && placeholder.classList.contains('image-placeholder')) {
                    placeholder.style.display = 'none';
                }
            }
        })
        .catch(error => {
            console.log('获取活动图片URL失败:', error);
        });
}
</script>
{% endblock %}
